<template>
	<div class="course-words-list" :class="[`words-list-${props.className}`]">
		<div v-if="$slots.header"><slot name="header" /></div>
		<div class="course-words-body">
			<div v-for="(item, index) in svgWords" :key="item.path">
				<div v-if="getPingYi" class="course-words-pinyi">
					<Pingyi v-bind="$attrs"><span>{{ getPingYi[index] }}</span></Pingyi>
				</div>
				<div class="course-words-box" :class="[{'filter-blur':isFilterBlur}, {'is-words-border': borderDraw}]"  :style="[classSize]" @click="handelViewWords(item)">
					<WordsDraw ref="wordsDrawRef" :words="item.words" />
					<img class="remote-svg" v-if="item.words && item.path" :src="transformSvgToBase64(item.path)" mode="widthFix" />
					<div v-else class="words-text">{{ item.words }}</div>
				</div>
			</div>
		</div>
		<div class="text-left margin-top-32" v-if="$slots.footer"><slot name="footer" /></div>
	</div>
</template>

<script setup>
	import { computed, onMounted, ref, watch } from "vue";
	import { Base64 } from 'js-base64';
	import axios from "axios"
	import { textToUnicode } from "@/utils";
	import { jsonFile } from "@/api"
	import WordsDraw from "./draw.vue"
	import Pingyi from "./pingyi.vue"
	const props = defineProps({
		size: {
			type: [String, Number],
			default: "default"
		},
		text: {
			type: String,
			default: ""
		},
		className: {
			type: String,
			default: ''
		},
		pingYi: {
			type: String,
			default: ''
		},
		borderDraw: {
			type: Boolean,
			default: true
		},
		blank: Boolean,
		disabled: Boolean,
		print: Boolean,
		blankLength: {
			type: Number,
			default: 0
		},
		showInput: Boolean,
		showPingYi: Boolean,
		isViewWords: Boolean,
		isDraw: Boolean,
		isCorrect: Boolean,
		filterBlur: Boolean,
	})
	const idx = ref(0)
	const svgWords = ref([]);
	const viewWordsSvg = ref('')
	const viewWords = ref('')
	const wordsDrawRef = ref(null)
	const viewWordsDrawRef = ref(null)
	const getPingYi = computed(() => props.pingYi)
	const isFilterBlur = computed(() => props.filterBlur)
	const classSize = computed(() => {
		const isNumber = Object.prototype.toString.call(props.size) === '[object Number]'
		if(isNumber) {
			if(props.print) {
				return { 'width': `${props.size}px`, 'height': `${props.size}px`}
			}else{
				return { 'width': `${props.size/2}rem`, 'height': `${props.size/2}rem`}
			}
			
		}else{
			return `course-words-size__${props.size}`
		}
		
	})
	const startDraw = (type) => {
		if(type === 'view') {
			viewWordsDrawRef.value?.startDraw()
			return
		}
		wordsDrawRef.value[0]?.startDraw()
	}
	const createData = () => {
		getWordsSvg().then(res => {
			svgWords.value = res
		})
		// // 长度
		// const length = props.text.length;
		// const arr = []
		// for(let i = 0; i < length; i++) {
		// 	const code = textToUnicode(props.text[i])
		// 	const path = `https://file.web-jshtml.cn/uploads/times/yuwen/wordssvg/${props.text[i]}.svg`

		// 	arr.push({
		// 		path,
		// 		words: props.text[i]
		// 	})
		// }
		// svgWords.value = arr
	}

	const getWordsSvg = () => {
		// 索引
		let idx = 0;
		const resourcesAudio = []
		return new Promise((resolve, reject) => {
			// 递归获取
			function getWordSvg(){
				if(props.text[idx]) {
					new Promise((resolve, reject) => {
						if(['。', '，'].includes(props.text[idx])) {
							idx++
							getWordSvg()
							return
						}	
						const path = `https://file.web-jshtml.cn/times/cnchar-data/draw/${props.text[idx]}.json`
						axios.get(path, { responseType: 'text' }).then(res => {
							const data = JSON.parse(res.data)
							let svgPath = `<svg width="60" height="60" fill="none" xmlns="http://www.w3.org/2000/svg" style="border: 10rpx solid #ddd; background-color: rgb(255, 255, 255);"><g transform="translate(5, 48.9453125) scale(0.048828125, -0.048828125)">`
							let path = ''
							data.strokes.forEach((s, i) => {
								const fill = 'fill:rgb(0, 0, 0)'
								path += `<path d="${s}" style="${fill};"></path>`
							})
							svgPath += `${path}</g></svg>`
							
							resourcesAudio.push({
								path: svgPath,
								words: props.text[idx]
							})
							idx++
							getWordSvg()
						}).catch(() => {
							resourcesAudio.push({
								path: '',
								words: props.text[idx]
							})
							idx++
							getWordSvg()
							console.log('404', props.text[idx])
						})
					})
				}else{
					if(idx >= props.text.length) {
						resolve(resourcesAudio)
						return
					}else{
						resourcesAudio.push({
							path: "",
							words: ""
						})
						idx++
						getWordSvg()
					}
				}
			}
			getWordSvg()
		})
	}

	
	const transformSvgToBase64 = (svgTxt) => {
		return 'data:image/svg+xml;base64,' + Base64.encode(svgTxt);
	}
	const handelViewWords = (data) => {
		if(props.isViewWords) {
			viewWordsSvg.value = data.path
			viewWords.value = data.words
		}
	}
	onMounted(() => {
		createData()
	})
	
	watch(() => props.text, (val) => {
		createData()
	}, {
		immediate: true
	})
	
	defineExpose({ startDraw })
</script>

<style lang="scss" scoped>
	.course-words-list {
		display: inline-flex;
		flex-wrap: wrap;
		flex-direction: column;
		.course-words-box {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			z-index: 2;
			width: 4rem;
			height: 4rem;
			box-sizing: border-box;
			background-color: #fff;
			margin: -1px 0 0 -1px;
			img {
				width: 78%;
				height: 78%;
			}
			span {
				transform: scale(3.6);
				font-size: 0.5rem;
			}
			&.is-words-border {
				border: 1px solid #d0d0d0;
				&:after,
				&:before {
					content: "";
					position: absolute;
					z-index: -1;
				}
					
				&:after {
					border-top: 1px dashed rgb(179 179 179);
					left: 0;
					right: 0;
					top: 50%;
					transform: scaleY(0.5);
				}
					
				&:before {
					border-left: 1px dashed rgb(179 179 179);
					top: 0;
					bottom: 0;
					left: 50%;
					transform: scaleX(0.5);
				}
			}
		}
	}
	.course-words-body {
		display: inline-flex;
		flex-wrap: wrap;
	}
</style>